<template>
  <div class="draw-management">
    <div class="match-info" v-if="matchInfo">
      <h2>比赛信息</h2>
      <div class="info-grid">
        <div>比赛日期：{{ formatDate(matchInfo.match_date) }}</div>
        <div>比赛时间：{{ matchInfo.match_time }}</div>
        <div>主场学校：{{ matchInfo.home_school_name }}</div>
        <div>客场学校：{{ matchInfo.away_school_name }}</div>
        <div>比赛场地：{{ matchInfo.venue_name }}</div>
      </div>
    </div>

    <div class="draw-section">
      <div class="left-panel">
        <h3>可选选手</h3>
        <div class="player-list">
          <div v-for="player in availablePlayers" :key="player.id" class="player-item">
            <div class="player-info">
              <span>{{ player.name }}</span>
              <span class="school-name">{{ player.school_name }}</span>
            </div>
            <el-button 
              type="primary" 
              size="small"
              @click="selectPlayer(player)"
              :disabled="isPlayerDrawn(player.id)"
            >
              选择
            </el-button>
          </div>
        </div>
      </div>

      <div class="right-panel">
        <h3>抽签结果</h3>
        <div class="draw-results">
          <el-table :data="drawResults" style="width: 100%">
            <el-table-column prop="draw_number" label="抽签号" width="80" />
            <el-table-column prop="player_name" label="选手姓名" />
            <el-table-column prop="school_name" label="学校" />
            <el-table-column prop="seat_number" label="座位号" width="80" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteDrawResult(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <div class="seating-arrangement">
      <h3>座位安排图</h3>
      <div class="seating-grid">
        <div class="top-row">
          <div 
            v-for="n in 5" 
            :key="n"
            class="seat"
            :class="{ occupied: getSeatInfo(2*n-1) }"
          >
            <template v-if="getSeatInfo(2*n-1)">
              <div class="seat-number">{{ getSeatInfo(2*n-1).draw_number }}</div>
              <div class="player-name">{{ getSeatInfo(2*n-1).player_name }}</div>
              <div class="school-name">{{ getSeatInfo(2*n-1).school_name }}</div>
            </template>
            <template v-else>
              <div class="seat-number">{{ 2*n-1 }}</div>
              <div class="empty-seat">空座位</div>
            </template>
          </div>
        </div>
        <div class="bottom-row">
          <div 
            v-for="n in 5" 
            :key="n"
            class="seat"
            :class="{ occupied: getSeatInfo(2*n) }"
          >
            <template v-if="getSeatInfo(2*n)">
              <div class="seat-number">{{ getSeatInfo(2*n).draw_number }}</div>
              <div class="player-name">{{ getSeatInfo(2*n).player_name }}</div>
              <div class="school-name">{{ getSeatInfo(2*n).school_name }}</div>
            </template>
            <template v-else>
              <div class="seat-number">{{ 2*n }}</div>
              <div class="empty-seat">空座位</div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 抽签号输入对话框 -->
    <el-dialog
      v-model="drawNumberDialogVisible"
      title="输入抽签号"
      width="30%"
    >
      <el-form :model="drawForm" label-width="80px">
        <el-form-item label="抽签号">
          <el-input-number 
            v-model="drawForm.draw_number" 
            :min="1" 
            :max="10"
            :disabled="drawNumbersInUse.includes(drawForm.draw_number)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawNumberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDraw" :disabled="!isValidDrawNumber">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DrawManagement',
  setup() {
    const route = useRoute()
    const matchId = route.params.id
    const matchInfo = ref(null)
    const availablePlayers = ref([])
    const drawResults = ref([])
    const drawNumberDialogVisible = ref(false)
    const drawForm = ref({
      player_id: null,
      draw_number: 1
    })

    // 获取比赛信息
    const fetchMatchInfo = async () => {
      try {
        const response = await fetch(`/api/matches/${matchId}`)
        matchInfo.value = await response.json()
      } catch (error) {
        ElMessage.error('获取比赛信息失败')
      }
    }

    // 获取可选选手
    const fetchAvailablePlayers = async () => {
      try {
        const response = await fetch(`/api/matches/${matchId}/available-players`)
        availablePlayers.value = await response.json()
      } catch (error) {
        ElMessage.error('获取可选选手失败')
      }
    }

    // 获取抽签结果
    const fetchDrawResults = async () => {
      try {
        const response = await fetch(`/api/matches/${matchId}/draw-results`)
        drawResults.value = await response.json()
      } catch (error) {
        ElMessage.error('获取抽签结果失败')
      }
    }

    // 选择选手
    const selectPlayer = (player) => {
      drawForm.value.player_id = player.id
      drawNumberDialogVisible.value = true
    }

    // 确认抽签
    const confirmDraw = async () => {
      try {
        const response = await fetch(`/api/matches/${matchId}/draw-results`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(drawForm.value)
        })
        
        if (!response.ok) {
          const error = await response.json()
          throw new Error(error.error)
        }

        const result = await response.json()
        drawResults.value.push(result)
        drawNumberDialogVisible.value = false
        ElMessage.success('抽签成功')
      } catch (error) {
        ElMessage.error(error.message)
      }
    }

    // 删除抽签结果
    const deleteDrawResult = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这条抽签记录吗？')
        
        const response = await fetch(`/api/matches/${matchId}/draw-results/${row.id}`, {
          method: 'DELETE'
        })
        
        if (!response.ok) {
          const error = await response.json()
          throw new Error(error.error)
        }

        drawResults.value = drawResults.value.filter(item => item.id !== row.id)
        ElMessage.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message)
        }
      }
    }

    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN')
    }

    // 判断选手是否已抽签
    const isPlayerDrawn = (playerId) => {
      return drawResults.value.some(result => result.player_id === playerId)
    }

    // 获取座位信息
    const getSeatInfo = (seatNumber) => {
      return drawResults.value.find(result => result.seat_number === seatNumber)
    }

    // 已使用的抽签号
    const drawNumbersInUse = computed(() => {
      return drawResults.value.map(result => result.draw_number)
    })

    // 判断抽签号是否有效
    const isValidDrawNumber = computed(() => {
      return drawForm.value.draw_number >= 1 && 
             drawForm.value.draw_number <= 10 && 
             !drawNumbersInUse.value.includes(drawForm.value.draw_number)
    })

    onMounted(() => {
      fetchMatchInfo()
      fetchAvailablePlayers()
      fetchDrawResults()
    })

    return {
      matchInfo,
      availablePlayers,
      drawResults,
      drawNumberDialogVisible,
      drawForm,
      selectPlayer,
      confirmDraw,
      deleteDrawResult,
      formatDate,
      isPlayerDrawn,
      getSeatInfo,
      drawNumbersInUse,
      isValidDrawNumber
    }
  }
}
</script>

<style scoped>
.draw-management {
  padding: 20px;
}

.match-info {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 15px;
}

.draw-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.left-panel, .right-panel {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.player-list {
  max-height: 400px;
  overflow-y: auto;
}

.player-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.player-info {
  display: flex;
  flex-direction: column;
}

.school-name {
  font-size: 12px;
  color: #666;
}

.seating-arrangement {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.seating-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.top-row, .bottom-row {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.seat {
  width: 150px;
  height: 100px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.seat.occupied {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.seat-number {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.empty-seat {
  color: #909399;
}

.player-name {
  font-weight: bold;
}

.school-name {
  font-size: 12px;
  color: #666;
}
</style> 